//
//  CareViewController.m
//  MZJ
//
//  Created by XDD on 16/6/4.
//  Copyright © 2016年 XDD. All rights reserved.
//

#import "CareViewController.h"
#import "CareCell.h"
#import "CareDetailVC.h"
#import "MJRefresh.h"
#import "ActiveTypeView.h"

@interface CareViewController ()<UITableViewDelegate,UITableViewDataSource> {
    NSInteger page;
    NSString *pandun_All_Str;

}

@property (nonatomic, strong) UITableView *care_TabelView;
@property (nonatomic, strong) NetWorkingSModel *model;
@property (nonatomic, strong) ModelViewController *modelViewController;
@property (nonatomic, strong) NSMutableArray *allarr;
@property (nonatomic, strong) NSArray *arr2;
@property (nonatomic, strong) UILabel *activeType_Label;
@property (nonatomic, strong) ActiveTypeView *activeTypeView;

@end

@implementation CareViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    self.navigationController.navigationBarHidden = YES;
    self.tabBarController.tabBar.hidden = YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    [GiFHUD show];
    // Do any additional setup after loading the view.
    self.topBar.backgroundColor = [UIColor colorWithRed:253/255.0 green:179/255.0 blue:10/255.0 alpha:1];
    self.titleLabel.text = @"关爱活动";
    self.view.backgroundColor = [UIColor colorWithRed:245/255.0 green:245/255.0 blue:245/255.0 alpha:1];
    [self.backButton setTitle:@"" forState:UIControlStateNormal];
    
    self.care_TabelView = [[UITableView alloc]initWithFrame:CGRectMake(0, 55+22, kWidth, kHeight - 55-22)];
    self.care_TabelView.backgroundColor = [UIColor colorWithRed:245/255.0 green:245/255.0 blue:245/255.0 alpha:1];
    self.care_TabelView.delegate = self;
    self.care_TabelView.dataSource = self;
    [self.care_TabelView registerNib:[UINib nibWithNibName:@"CareCell" bundle:nil] forCellReuseIdentifier:@"careCell"];
    self.care_TabelView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:self.care_TabelView];
    
    //按活动类型
    UIButton *activeTYypeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    activeTYypeBtn.frame = CGRectMake(kWidth/3 - 30, 9 + 55, kWidth/3 + 60, 16);
    activeTYypeBtn.layer.borderWidth = 1.0;
    activeTYypeBtn.backgroundColor = [UIColor whiteColor];
    [activeTYypeBtn addTarget:self action:@selector(activeTYypeBtnAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:activeTYypeBtn];
    
    _activeType_Label = [[UILabel alloc]initWithFrame:CGRectMake(3, 1, kWidth/3 + 60 - 20, 14)];
    _activeType_Label.textAlignment = NSTextAlignmentCenter;
    _activeType_Label.text = @"按活动类型";
    _activeType_Label.font = [UIFont systemFontOfSize:10];
    [activeTYypeBtn addSubview:_activeType_Label];
    
    UIImageView *activeTYype_ImageView = [[UIImageView alloc]initWithFrame:CGRectMake(activeTYypeBtn.frame.size.width - 11, 3, 8, 10)];
//    activeTYype_ImageView.backgroundColor = [UIColor purpleColor];
    activeTYype_ImageView.image = [UIImage imageNamed:@"arrow_Left_Img"];

    [activeTYypeBtn addSubview:activeTYype_ImageView];
    
    //搜索按钮
    UIButton *searchBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    searchBtn.frame = CGRectMake(kWidth*2/3 + 40, 9 + 53, 20, 20);
    //    searchBtn.layer.borderWidth = 1.0;
    [searchBtn setImage:[UIImage imageNamed:@"search_img@2x"] forState:UIControlStateNormal];
    //    searchBtn.backgroundColor = [UIColor redColor];
    [searchBtn addTarget:self action:@selector(searchBtnAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view  addSubview:searchBtn];
    
    pandun_All_Str = @"NOALL";

    page = 1;
    _allarr = [NSMutableArray array];
    //调网络请求接口
    if (!_modelViewController) {
        _modelViewController = [[ModelViewController alloc]init];
        if (!_model) {
            
            _model = [[NetWorkingSModel alloc] init];
            
            [self requestnetwork];
        }
    }
    
    //下拉刷新
    self.care_TabelView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        _allarr = nil;
        if (_allarr == nil) {
            //            _allarr = [NSMutableArray array];
            page = 1;
            [self requestnetwork];
        }
        // 结束刷新
        [self.care_TabelView.mj_header endRefreshing];
        
    }];
    
    // 设置自动切换透明度(在导航栏下面自动隐藏)
    self.care_TabelView.mj_header.automaticallyChangeAlpha = YES;
    
    
    // 上拉刷新
    self.care_TabelView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        
        page++;
        [self requestnetwork];
        //        // 结束刷新
        [self.care_TabelView.mj_footer endRefreshing];
    }];


}

- (void)activeTYypeBtnAction {
    self.activeTypeView.hidden = NO;
    _activeTypeView.mBview_type.hidden = NO;
}

- (void)searchBtnAction {
    _allarr = nil;
    pandun_All_Str = @"YESALL";
    if (_allarr == nil) {
        //            _allarr = [NSMutableArray array];
        page = 1;
    }

    
    __weak typeof (self)weakSelf = self;
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    
    [dic setObject:[NSString stringWithFormat:@"%ld",(long)page] forKey:@"page"];
    
    if (!IsNilString([DataModel object].care_Activetype_ID_Str)) {
        
        [dic setObject:[DataModel object].care_Activetype_ID_Str forKey:@"acneed"];
        
    }
    
    [_model setBlockWithReturnBlock:^(id returnValue) {
        
        NSLog(@"关爱活动 = %@",returnValue);
        weakSelf.arr2 = returnValue[@"result"];
        
        if ( page == 1) {
            weakSelf.allarr = [NSMutableArray array];
        }
        [weakSelf.allarr addObjectsFromArray:weakSelf.arr2];
        
        [weakSelf.care_TabelView reloadData];
        [weakSelf.care_TabelView.mj_footer resetNoMoreData];
        
    } WithErrorBlock:^(id errorCode) {
        NSLog(@"没有更多数据");
        NSLog(@"%@",errorCode);
        // 结束刷新
        [weakSelf.care_TabelView.mj_footer endRefreshingWithNoMoreData];
    }];
    [weakSelf.model homeAppGetactivity:dic];

}

- (ActiveTypeView *)activeTypeView {
    if (!_activeTypeView) {
        _activeTypeView = [[ActiveTypeView alloc]initWithFrame:CGRectMake(0, 55, kWidth, kHeight - 55 - 44)];
        [self.view addSubview:_activeTypeView];
        
        __weak typeof (self)weakSelf = self;
        
        [_activeTypeView setDidsingleTapClickActionBlock:^{
            weakSelf.activeTypeView.mBview_type.hidden = YES;
            weakSelf.activeTypeView.hidden = YES;
        }];
        
        [_activeTypeView setDidactiveType_Name_ClickActionBlock:^{
            weakSelf.activeTypeView.mBview_type.hidden = YES;
            weakSelf.activeTypeView.hidden = YES;
            weakSelf.activeType_Label.text = [DataModel object].care_Activetype_Name_Str;
//            [weakSelf.care_TabelView reloadData];
        }];
        [_activeTypeView setDidactiveType_ButtonActionBlock:^{
            weakSelf.activeTypeView.mBview_type.hidden = YES;
            weakSelf.activeTypeView.hidden = YES;
            weakSelf.activeType_Label.text = [DataModel object].care_Activetype_Name_Str;

        }];
    }
    return _activeTypeView;
}

-(void)requestnetwork{
    
    __weak typeof (self)weakSelf = self;
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    
    [dic setObject:[NSString stringWithFormat:@"%ld",(long)page] forKey:@"page"];
    
    if ([pandun_All_Str isEqualToString:@"NOALL"]) {
        [dic setObject:@"1" forKey:@"all"];
    }
    
    [_model setBlockWithReturnBlock:^(id returnValue) {
        
        NSLog(@"关爱活动 = %@",returnValue);
        weakSelf.arr2 = returnValue[@"result"];
        
        if ( page == 1) {
            weakSelf.allarr = [NSMutableArray array];
        }
        [weakSelf.allarr addObjectsFromArray:weakSelf.arr2];
        
        [weakSelf.care_TabelView reloadData];
        [weakSelf.care_TabelView.mj_footer resetNoMoreData];
        
    } WithErrorBlock:^(id errorCode) {
        NSLog(@"没有更多数据");
        NSLog(@"%@",errorCode);
        // 结束刷新
        [weakSelf.care_TabelView.mj_footer endRefreshingWithNoMoreData];
    }];
    [weakSelf.model homeAppGetactivity:dic];
    [GiFHUD dismiss];

}

//点击返回键
- (void)clickedBackButton:(UIButton *)sender {
    
    [self.navigationController popViewControllerAnimated:YES];
    self.tabBarController.tabBar.hidden = NO;
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return _allarr.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 90;
}

//Header的高度
- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForHeaderInSection:(NSInteger)section {
//    if (section == 0) {
//        return 1;
//    }
    return 3;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    UIView *head = [[UIView alloc]init];
//    if (section == 0) {
//        head.frame = XJFlexibleFrame(CGRectMake(0, 0, 320, 1), NO);
//        head.backgroundColor = [UIColor colorWithRed:245/255.0 green:245/255.0 blue:245/255.0 alpha:1];
//        
//        UIView *searchView = [[UIView alloc]initWithFrame:XJFlexibleFrame(CGRectMake(50, 4, 220, 26), NO)];
//        searchView.backgroundColor = [UIColor whiteColor];
//        searchView.layer.cornerRadius = 13.0*XJVerticalMultiplier();
//        searchView.layer.masksToBounds = YES;
//        searchView.layer.borderWidth = 1.0;
//        searchView.layer.borderColor = [[UIColor grayColor]CGColor];
//        [head addSubview:searchView];
//        
//        UITextField *searchTextfd = [[UITextField alloc]initWithFrame:XJFlexibleFrame(CGRectMake(10, 6, 165, 16), NO)];
//        searchTextfd.placeholder = @"请输入可捐款,志愿者参加活动";
//        //        searchTextfd.layer.cornerRadius = 15.0*XJVerticalMultiplier();
//        //        searchTextfd.layer.masksToBounds = YES;
//        searchTextfd.backgroundColor = [UIColor yellowColor];
//        searchTextfd.font = [UIFont systemFontOfSize:11];
//        [searchView addSubview:searchTextfd];
//        
//        UIButton *searchBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
//        searchBtn.frame = XJFlexibleFrame(CGRectMake(180, 2, 38, 22), NO);
//        searchBtn.backgroundColor = [UIColor greenColor];
//        [searchView addSubview:searchBtn];
//        
//        UIImageView *searchImageView = [[UIImageView alloc]initWithFrame:XJFlexibleFrame(CGRectMake(13, 0, 22, 22), YES)];
//        searchImageView.backgroundColor = [UIColor purpleColor];
//        searchImageView.layer.masksToBounds = YES;
//        searchImageView.layer.cornerRadius = 11.0*XJVerticalMultiplier();
//        [searchBtn addSubview:searchImageView];
        
//        return head;
//    }else {
        head.frame = CGRectMake(0, 0, kWidth, 3);
        head.backgroundColor = [UIColor colorWithRed:245/255.0 green:245/255.0 blue:245/255.0 alpha:1];
        
        return head;
//    }
    
//    return 0;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
//    NSInteger section = indexPath.section;
    
    static NSString *identifier = @"careCell";
    CareCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    //    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    if (!cell) {
        
        cell = [[CareCell alloc] initWithFrame:CGRectZero];
    }
    cell.nameLabel.text = _allarr[indexPath.section][@"acname"];
    cell.detailLabel.text = [NSString stringWithFormat:@"项目简介：%@",_allarr[indexPath.section][@"acdescription"]];
    [cell.headImageView sd_setImageWithURL:[NSURL URLWithString:_allarr[indexPath.section][@"acimg"]]
                          placeholderImage:[UIImage imageNamed:@"placeholder.png"]];
    NSString *date_Str =  [NSString stringWithFormat:@"%@",_allarr[indexPath.section][@"actime"]];
    if ([date_Str intValue] == 0) {
        cell.dateLabel.text = @"";
    } else {
        cell.dateLabel.text = [_modelViewController TimeStamp:_allarr[indexPath.section][@"actime"] form_time:@"yyyy-MM-dd"];

    }
    cell.loveNumLabel.text = [NSString stringWithFormat:@"累计爱心%@次",_allarr[indexPath.section][@"count"]];
    
    NSString *ss = [NSString stringWithFormat:@"累计爱心%@次",_allarr[indexPath.section][@"count"]];
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:ss];
    //设置颜色
    [attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(4, ss.length - 5)]; // 0为起始位置 length是从起始位置开始 设置指定颜色的长度
    cell.loveNumLabel.attributedText = attributedString;
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    CareDetailVC *careDetailVC = [[CareDetailVC alloc]init];
    [DataModel object].care_ID_Str = [NSString stringWithFormat:@"%@",_allarr[indexPath.section][@"acid"]];
    [self.navigationController pushViewController:careDetailVC animated:YES];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
